﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.DepartmentCommand;
using D.Medicalcare.Read.API.Dtos;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.DepartmentHarder
{
    public class GetDepartmentHarder : IRequestHandler<GetDepartmentCommand, APIPaging<DepartmentDto>>
    {

        private readonly IBaseRepository<Department> repository;
        private readonly IBaseRepository<HospitalNavigation> baseRepository;

        public GetDepartmentHarder(IBaseRepository<Department> repository, IBaseRepository<HospitalNavigation> baseRepository)
        {
            this.repository = repository;
            this.baseRepository = baseRepository;
        }

        public async Task<APIPaging<DepartmentDto>> Handle(GetDepartmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIPaging<DepartmentDto> result = new APIPaging<DepartmentDto>();
                result.Code = APIEnum.Mvc;
                result.Msg = "查询成功";
                var list = from a in repository.GetAll()
                           join b in baseRepository.GetAll() on a.CampusId equals b.HospitalNavigationId
                         select new DepartmentDto
                           {
                            DeparId =a.DeparId,
                            DeparName=a.DeparName,
                            CampusId=b.HospitalNavigationId,
                            CampusName=b.CampusName,
                            SuperAffiliation =a.SuperAffiliation,  
                            Doctorlocation =a.Doctorlocation,  
                            Deparstate=a.Deparstate 
                  };



                if (request.DeparId!=null)
                {
                    list = list.Where(a => a.DeparId == request.DeparId);

                }




                result.Count = list.Count();
                result.PageCount = (int)Math.Ceiling(result.Count * 1.0 / request.PageSize);
                result.Data = list.OrderByDescending(a => a.DeparId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
